package com.ck.company.controller.client;

import com.ck.annotation.PermissionRequired;
import com.ck.company.service.CpPictureService;
import com.ck.constant.FileConstant;
import com.ck.constant.PageConstant;
import com.ck.constant.RequestConstant;
import com.ck.constant.ResponseConstant;
import com.ck.model.common.User;
import com.ck.model.common.sys.JsonResponse;
import com.ck.model.company.vo.CpProgramPictureListVO;
import com.github.pagehelper.Page;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 编辑节目客户端-图片
 *
 * @author linqiang
 * @version v1.0
 * @date 2018-09-19 16:16
 */
@PermissionRequired
@Controller
@RequestMapping("/client/picture")
public class CpPictureClientController {

    private static Logger logger = LoggerFactory.getLogger(CpPictureClientController.class);
    @Autowired
    private CpPictureService cpPictureService;


    /**
     * 上传图片
     */
    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Object upload(@RequestParam("files") MultipartFile files, HttpServletRequest request) {
        try {
            //获取文件全名称
            String originalFilename = files.getOriginalFilename();
            if (StringUtils.isBlank(originalFilename)) {
                return new JsonResponse(ResponseConstant.CODE_FAIL, "文件名不能为空");
            }
            //去掉后缀，获取纯文件名
            String extension = FilenameUtils.getExtension(originalFilename);
            //校验文件后缀是否是图片
            if (!FileConstant.IMAGE_SUFFIX_LIST.contains(extension)) {
                return new JsonResponse(ResponseConstant.CODE_FAIL, "文件格式不正确，请上传图片文件");
            }
            String fileName = originalFilename.replaceAll("." + extension, "").trim();
            if (StringUtils.isBlank(fileName)) {
                return new JsonResponse(ResponseConstant.CODE_FAIL, "文件名不能为空");
            }
            Map<String, Object> fileMsgMap = cpPictureService.savePicture(files, request);
            return new JsonResponse(ResponseConstant.CODE_SUCCESS, fileMsgMap, "上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpPictureClientController upload 上传图片失败：" + e.getMessage());
        }
        return new JsonResponse(ResponseConstant.CODE_FAIL, "上传失败");
    }


    /**
     * 上传场景背景图片
     */
    @ResponseBody
    @RequestMapping(value = "/upload/scene/background", method = RequestMethod.POST)
    public Object uploadForSceneBackground(@RequestParam("files") MultipartFile files, HttpServletRequest request) {
        try {
            //获取文件全名称
            String originalFilename = files.getOriginalFilename();
            if (StringUtils.isBlank(originalFilename)) {
                return new JsonResponse(ResponseConstant.CODE_FAIL, "文件名不能为空");
            }
            //去掉后缀，获取纯文件名
            String extension = FilenameUtils.getExtension(originalFilename);
            //校验文件后缀是否是图片
            if (!FileConstant.IMAGE_SUFFIX_LIST.contains(extension)) {
                return new JsonResponse(ResponseConstant.CODE_FAIL, "文件格式不正确，请上传图片文件");
            }
            String fileName = originalFilename.replaceAll("." + extension, "").trim();
            if (StringUtils.isBlank(fileName)) {
                return new JsonResponse(ResponseConstant.CODE_FAIL, "文件名不能为空");
            }
            Map<String, Object> fileMsgMap = cpPictureService.uploadForSceneBackground(files, request);
            return new JsonResponse(ResponseConstant.CODE_SUCCESS, fileMsgMap, "上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpPictureClientController uploadForSceneBackground 上传图片失败：" + e.getMessage());
        }
        return new JsonResponse(ResponseConstant.CODE_FAIL, "上传失败");
    }

    /**
     * 图片列表ajax
     */
    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Object list(String pictureName, Long pictureGroupId, String currentGroupName, Integer pageNum,
                       Integer pageSize, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>(5);
        try {
            User user = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
            String companyCode = user.getCompanyCode();
            pageNum = (pageNum == null ? PageConstant.DEFAULT_PAGE_NUM : pageNum);
            pageSize = (pageSize == null ? PageConstant.DEFAULT_PAGE_SIZE : pageSize);
            Page<CpProgramPictureListVO> pageInfo = cpPictureService.listProgramPicture(companyCode, pictureGroupId, pageNum, pageSize);
            result.put("pictureName", pictureName);
            result.put("pictureGroupId", pictureGroupId);
            result.put("currentGroupName", currentGroupName);
            result.put("data", pageInfo.getResult());
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            result.put("total", pageInfo.getTotal());
            return new JsonResponse(ResponseConstant.CODE_SUCCESS, result, "查询成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpPictureController listPictureAjax 查询图片列表失败：" + e.getMessage());
        }
        return new JsonResponse(ResponseConstant.CODE_FAIL, "查询失败");
    }

}
